package com.situ.hotel.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.situ.hotel.entity.Result;
import com.situ.hotel.entity.User;
import com.situ.hotel.service.UserService;

@RestController
@RequestMapping("/api/user")
public class UserController {

	@Autowired
	private UserService userService;

	@PostMapping({"/add","/reg"})
	public Result add(User user) {
		try {
			userService.add(user);
			return Result.success(1,user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error(-1, e.getMessage());
		}
	}
	@PostMapping("/edit")
	public Result edit(User user) {
		try {
			userService.edit(user);
			return Result.success(1, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error(-1, e.getMessage());
		}
	}
	
	
	@GetMapping("/search")
	public Result search(Integer page,Integer limit, User user) {
		if(page==null) {
			List<User>list=userService.search(user);
			return Result.success(0, list);
		}else {
			PageInfo pageInfo=userService.searchByPage(page, limit, user);
			return Result.success(0, pageInfo);
		}
	}
	@PostMapping("/login")
	public Result login(User user, HttpSession session) {
		try {
			user = userService.login(user);
			session.setAttribute("user", user);
			return Result.success(1, user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Result.error(-1, e.getMessage());
		}
	}
	
	@GetMapping("/logout")
	public Result logout( HttpSession session) {
		session.invalidate();
		return Result.success(1, null);
	}
	
	@GetMapping("/loginUser")
	public Result loginUser(HttpSession session) {
		User user =(User)session.getAttribute("user");
		if(user!=null) {
			return Result.success(1, user);
		}else {
			return Result.error(-1,null);
		}
	}
}
